import { computeFormulaApi, getFormulaApi } from "@/api/formula";
import dayjs from "dayjs";
import { handleError } from "./handleError";

export async function getFormulaList(company_id, usage) {
    const formulaResponse = await getFormulaApi(company_id);
    if (usage) {
        return formulaResponse.data.filter(formula => formula.usage === usage);
    } else {
        return formulaResponse.data;
    }
}
export async function getFormulaData(formulaList, dateColumns, type = "day") {
    const formulaData = await Promise.all(
        formulaList.map(async (formula) => {
            const localFormula = { ...formula };
            // 等待所有日期的计算完成
            await Promise.all(
                dateColumns.map(async (date, index) => {
                    const result = await calculateFormulaValue(formula, date, type);
                    localFormula['usage_' + index] = result;
                    return result;
                })
            );
            return localFormula;
        })
    );
    return formulaData;
}
//计算单个值在指定日期的结果
export async function calculateFormulaValue(formula, date, type = "day") {
    //date转换为range
    let start_time = dayjs(date).startOf(type).valueOf();
    let end_time = dayjs(date).endOf(type).valueOf();
    try {
        let { data } = await computeFormulaApi({
            id: formula.id,
            start_time,
            end_time
        })
        return data
    } catch (error) {
        handleError(error, '计算公式值出错');
    }
}